package co.chuangdian.oflauncher;

import co.chuangdian.oflauncher.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.umeng.update.UmengUpdateAgent;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout.LayoutParams;
import android.widget.Toast;
import cn.onekit.*;
import co.chuangdian.oflauncher.uc.AppCard;
import co.chuangdian.oflauncher.uc.FolderAppsAdapter;
import co.chuangdian.oflauncher.uc.FolderAppsGridView;
import co.chuangdian.oflauncher.uc.FolderAppsAdapter.OnCoverChangeListener;
import co.chuangdian.oflauncher.uc.FolderAppsAdapter.OnModeChangeListener;
import co.chuangdian.oflauncher.uc.FolderAppsGridView.OnDragListener;
import co.chuangdian.oflauncher.uc.FolderAppsGridView.OnLongPressListener;
import co.chuangdian.oflauncher.uc.FolderAppsGridView.ScrollViewListener;
import co.chuangdian.oflauncher.uc.FolderSideBar;
import co.chuangdian.oflauncher.widgets.system.ContanctsWidget;
import co.chuangdian.oflauncher.widgets.system.MusicPlayWidget;
import uc.BlurImageView;
import uc.IconView;
import uc.allapp.AllAppActivity;

public class MainActivity extends OFActivity {
	public static JSONObject alias;
	private FolderAppsGridView appsGridView;
	private FolderAppsAdapter appsAdpater;
	private BlurImageView coverImageView;
	private BlurImageView appsGridViewBG;
	JSONArray folders;
	int folderIndex = 0;
	JSONObject folder;
	JSONObject setting;
	View foldersFragmentBox, widgetsFragmentBox;

	public static String getAlias(PackageInfo app) {
		String appID = app.packageName;
		String alias = MainActivity.alias.optString(appID);
		if (alias != null && alias != "") {
			return alias;
		}
		return (String) context.getPackageManager().getApplicationLabel(app.applicationInfo);
	}

	final static int REQUEST_UNINSTALL = 1;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		switch (requestCode) {
		case REQUEST_UNINSTALL: {
			if (resultCode == Activity.RESULT_OK) {
				Toast.makeText(this, "Uninstall succeeded!", Toast.LENGTH_SHORT).show();
				reloadApps();
			} else if (resultCode == Activity.RESULT_CANCELED) {
				Toast.makeText(this, "Uninstall canceled!", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(this, "Uninstall Failed!", Toast.LENGTH_SHORT).show();
			}
			break;
		}
		case 2:
			contanctsWidgetFragment.onActivityResult(requestCode, resultCode, intent);
			break;
		default:
			break;
		}
	}

	FolderSideBar sideBar_Left, sideBar_Right;

	void changeFolder() {
		folders = JSON.parses((String) CONFIG.get("folders"));
		folder = folders.optJSONObject(folderIndex);
		appsAdpater.setFolderIndex(folderIndex);
		reloadApps();
		updateCover();
	}

	void initSideBars() {
		setting = JSON.parse((String) CONFIG.get("setting"));
		leftDrawer.removeAllViews();
		rightDrawer.removeAllViews();

		switch (setting.optJSONObject("gestures").optInt("folders_widgets")) {

		case 1:

			leftDrawer.addView(foldersFragmentBox);
			rightDrawer.addView(widgetsFragmentBox);

			break;
		case 2:
			leftDrawer.addView(widgetsFragmentBox);
			rightDrawer.addView(foldersFragmentBox);
			break;
		default:
			break;
		}
	}
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		alias = JSON.parse((String) CONFIG.get("alias"));
		setting = JSON.parse((String) CONFIG.get("setting"));
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(this);
		setContentView(R.layout.main);
		//
		MESSAGE.receive("changeFolder", null, new CALLBACK<Bundle>() {

			@Override
			public void run(boolean isError, Bundle result) {
				folderIndex = result.getInt("index");
				changeFolder();
				drawerLayout.closeDrawer(leftDrawer);
			}
		});
		MESSAGE.receive("[setting]folders_widgets", null, new CALLBACK<Bundle>() {

			@Override
			public void run(boolean isError, Bundle result) {
				initSideBars();
			}
		});
		MESSAGE.receive("[setting]sidebars", null, new CALLBACK<Bundle>() {

			@Override
			public void run(boolean isError, Bundle result) {
				initSideBars();
				setting = JSON.parse((String) CONFIG.get("setting"));
			}
		});
		//
		initDrawers();
		//
		sideBar_Left = (FolderSideBar) this.findViewById(R.id.sideBar_Left);
		sideBar_Right = (FolderSideBar) this.findViewById(R.id.sideBar_Right);
		foldersFragmentBox = (View) this.findViewById(R.id.foldersFragmentBox);
		widgetsFragmentBox = (View) this.findViewById(R.id.widgetsFragmentBox);

		appsGridView = (FolderAppsGridView) this.findViewById(R.id.appsGridView);
		appsGridView.setOnLongPressListener(new OnLongPressListener() {

			@Override
			public void onLongPress(int index) {
				index-=index;
				PackageInfo app = apps.get(index);
				AppCard appCard = new AppCard(MainActivity.this, app, folder.optString("name"), new CALLBACK<String>() {

					@Override
					public void run(boolean isError, String appID) {
						if (isError) {
							Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
							intent.setData(Uri.parse("package:" + appID));
							intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
							startActivityForResult(intent, REQUEST_UNINSTALL);
						} else {
							JSONArray appIDs = folder.optJSONArray("appIDs");
							for (int i = 0; i < appIDs.length(); i++) {
								String id = appIDs.optString(i);
								if (appID.equalsIgnoreCase(id)) {
									appIDs.remove(i);
									reloadApps();
									break;
								}
							}
						}
					}
				});
				appCard.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss(DialogInterface dialog) {
						reloadApps();
					}
				});
				appCard.show();
			}

		});
		appsAdpater = new FolderAppsAdapter(this, appsGridView);

		appsAdpater.setOnModeChangeListener(new OnModeChangeListener() {

			@Override
			public void onModeChange(boolean mode) {
				addAppButton.setVisibility(mode || apps.size() <= 0 ? View.VISIBLE : View.GONE);
			}
		});
		appsAdpater.setOnCoverChangeListener(new OnCoverChangeListener() {

			@Override
			public void onCoverChange() {
				updateCover();

			}

		});
		appsGridView.setAdapter(appsAdpater);
		appsGridView.setOnDragListener(new OnDragListener() {

			@Override
			public void onSwat(int index2, int index1) {
				PackageInfo app1 = apps.get(index1);
				PackageInfo app2 = apps.get(index2);
				String appID1 = app1.packageName;
				String appID2 = app2.packageName;
				JSONArray temp = folder.optJSONArray("appIDs");
				for (int i = 0; i < temp.length(); i++) {
					try {
						String appID = temp.optString(i);
						if (appID.equalsIgnoreCase(appID1)) {
							temp.put(i, appID2);
						} else if (appID.equalsIgnoreCase(appID2)) {
							temp.put(i, appID1);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				try {
					folder.put("appIDs", temp);
					folders.put(folderIndex,folder);
					CONFIG.set("folders", folders);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onDraging(int direct) {
				if (direct == 0) {
					sideBar_Left.setVisibility(View.GONE);
					sideBar_Right.setVisibility(View.GONE);
					return;
				}
				final int sidebars = setting.optJSONObject("gestures").optInt("sidebars");
				if ((sidebars & direct) != 0) {
					switch (direct) {
					case 1:
						showSideBar(sideBar_Left, sideBar_Right, direct, true);
						break;
					case 2:
						showSideBar(sideBar_Right, sideBar_Left, direct, true);
						break;
					default:
						break;
					}
				} else {

				}
			}

			@Override
			public void onDraged(int direct, int appIndex, float x, float y) {
				if (direct == 0) {
					sideBar_Left.setVisibility(View.GONE);
					sideBar_Right.setVisibility(View.GONE);
					return;
				}
				final int sidebars = setting.optJSONObject("gestures").optInt("sidebars");
				if ((sidebars & direct) != 0) {
					switch (direct) {
					case 1:
						changeSideBar(sideBar_Left, appIndex, x, y);
						break;
					case 2:
						changeSideBar(sideBar_Right, appIndex, x, y);
						break;
					default:
						break;
					}
				} else {

				}
			}

		});
		appsGridView.setOnScrollViewListener(new ScrollViewListener() {

			@Override
			public void onScrollChanged(FolderAppsGridView scrollView, int x, int y) {
				updateScroll(x, y);
			}

		});
		appsGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				arg2 -= 3;
				if (arg2 < 0 || arg2 >= apps.size()) {
					return;
				}
				PackageInfo appInfo = apps.get(arg2);
				APP.openApp(appInfo.packageName);
			}

		});
		//
		coverImageView = (BlurImageView) this.findViewById(R.id.coverImageView);
		appsGridViewBG = (BlurImageView) this.findViewById(R.id.appsGridViewBG);
		//
		ViewTreeObserver vto = appsGridView.getViewTreeObserver();
		vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
			public boolean onPreDraw() {
				if (hasMeasured == false) {
					hasMeasured = true;
					int appsGridViewHeight = appsGridView.getMeasuredHeight();
					int marginTop = appsGridViewHeight - dp2px(IconView.HEIGHT) * 2;
					appsGridView.MARGIN_TOP = marginTop;
					appsAdpater.MARGIN_TOP = marginTop;
					changeFolder();
					updateScroll(0, 0);
				}
				return true;
			}
		});
		//
		this.findViewById(R.id.settingButton).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this, co.chuangdian.oflauncher.setting.HomeActivity.class);
				startActivity(intent);
			}
		});
		this.findViewById(R.id.folderSettingButton).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						co.chuangdian.oflauncher.folders.setting.HomeActivity.class);
				startActivity(intent);
			}
		});
		this.findViewById(R.id.widgetSettingButton).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						co.chuangdian.oflauncher.widgets.setting.HomeActivity.class);
				startActivity(intent);
			}
		});
		MESSAGE.receive(AllAppActivity.message, this.toString(), new CALLBACK<Bundle>() {

			@Override
			public void run(boolean isError, Bundle result) {
				JSONArray appIDs = JSON.parses(result.getString("appIDs"));
				try {
					folder.put("appIDs", appIDs);
					CONFIG.set("folders", folders);
					appsAdpater.setHeaderMode(false);
					reloadApps();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		});
		//
		addAppButton = (Button) this.findViewById(R.id.addAppButton);
		addAppButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				JSONArray appIDs = folder.optJSONArray("appIDs");
				Intent intent = new Intent(MainActivity.this, uc.allapp.AllAppActivity.class);
				intent.putExtra("receiver", MainActivity.this.toString());
				intent.putExtra("appIDs", JSON.stringify(appIDs));
				startActivity(intent);
			}

		});
		initSideBars();
	}

	void updateScroll(int x, int y) {
		coverImageView.setBlur(y / maxY);
		coverImageView.scrollTo(0, y / 2);
		appsGridViewBG.scrollTo(0, (int) Math.min(0, y - appsGridView.MARGIN_TOP));
		LayoutParams layoutParams = (LayoutParams) addAppButton.getLayoutParams();
		layoutParams.height = y + dp2px(IconView.HEIGHT * 2);
		addAppButton.setLayoutParams(layoutParams);
	}

	void showSideBar(FolderSideBar sideBar, FolderSideBar sideBar2, int direct, boolean show) {
		sideBar.mode = show;
		if (show) {
			sideBar.setVisibility(View.VISIBLE);
			sideBar2.setVisibility(View.GONE);
		} else {
			sideBar.setVisibility(View.GONE);
		}
	}

	void changeSideBar(FolderSideBar sideBar, int appIndex, float x, float y) {
		x -= sideBar.getLeft();
		y -= sideBar.getTop();
		String appID = apps.get(appIndex).packageName;
		JSONArray appIDs = folder.optJSONArray("appIDs");
		for (int i = 0; i < appIDs.length(); i++) {
			if (appIDs.optString(i).equalsIgnoreCase(appID)) {
				appIDs.remove(i);
				break;
			}
		}
		//
		final int folderIndex = sideBar.pointToPosition((int) x, (int) y);
		if (folderIndex < 0) {
			sideBar.setVisibility(View.GONE);
			return;
		}
		JSONObject temp = folders.optJSONObject(folderIndex);
		appIDs = temp.optJSONArray("appIDs");
		appIDs.put(appID);
		//
		CONFIG.set("folders", folders);
		sideBar.setVisibility(View.GONE);
		reloadApps();

	}

	void updateCover() {
		Bitmap cover = FSO.loadImage(FSO.photos(folder.optString("cover")).getPath(), false);
		//
		Bitmap cover_blur = IMAGE.blur(cover);
		coverImageView.setImage(cover);
		coverImageView.setBlurImage(cover_blur);
		Bitmap cover_blur2 = IMAGE.blur(cover, 150);
		Bitmap cover_reverse = IMAGE.reverse(cover_blur2);
		appsGridViewBG.setImage(cover_reverse);
	}

	Button addAppButton;
	boolean hasMeasured;
	List<PackageInfo> apps = new ArrayList<PackageInfo>();

	void reloadApps() {
		apps.clear();
		JSONArray json = folder.optJSONArray("appIDs");
		//
		Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
		mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		PackageManager packageManager = getPackageManager();
		for (int i=0;i<json.length();i++) {
			String appID = json.optString(i);
			try {
				PackageInfo app = packageManager.getPackageInfo(appID, 0);
				apps.add(app);
			} catch (NameNotFoundException e) {
			}
		}
		addAppButton.setVisibility(apps.size() > 0 ? View.GONE : View.VISIBLE);
		appsAdpater.setData(apps);
		//
		final int appsHeight = ((int) Math.ceil(apps.size() / 3) - 2) * dp2px(IconView.HEIGHT);
		maxY = Math.min(appsGridView.MARGIN_TOP, appsHeight);
		//
	}

	float maxY;

	void initFolders() {
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if (appsGridView.isHeaderPress) {
				appsAdpater.setHeaderMode(false);
				return true;
			} else if (addAppButton.getVisibility() == View.VISIBLE) {
				addAppButton.setVisibility(View.GONE);
				return true;
			} else {
				exitBy2Click(this);
				return true;
			}
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	private static Boolean isExit = false;

	public static void exitBy2Click(Activity context) {
		Timer tExit = null;
		if (isExit == false) {
			isExit = true; // 准备退出
			Toast.makeText(context, "再按一次退出程序", Toast.LENGTH_SHORT).show();
			tExit = new Timer();
			tExit.schedule(new TimerTask() {
				@Override
				public void run() {
					isExit = false; // 取消退出
				}
			}, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

		} else {
			context.finish();
			System.exit(0);
		}
	}

	public static DrawerLayout drawerLayout;
	ViewGroup leftDrawer, rightDrawer;
	public static ContanctsWidget contanctsWidgetFragment;
	public static MusicPlayWidget musicPlayWidgetFragment;

	void initDrawers() {
		drawerLayout = (DrawerLayout) this.findViewById(R.id.drawerLayout);
		leftDrawer = (ViewGroup) this.findViewById(R.id.leftDrawer);
		rightDrawer = (ViewGroup) this.findViewById(R.id.rightDrawer);
		drawerLayout.setDrawerListener(new DrawerListener() {

			@Override
			public void onDrawerClosed(View arg0) {
				appsGridView.setEnabled(true);
			}

			@Override
			public void onDrawerOpened(View arg0) {
			}

			@Override
			public void onDrawerSlide(View arg0, float arg1) {
				appsGridView.setEnabled(false);
			}

			@Override
			public void onDrawerStateChanged(int arg0) {
			}

		});

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		musicPlayWidgetFragment.onDestroy();
	}
}
